/**
 * @page: 账户安全
 */

import React, { useState, useEffect, useMemo, useRef } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Modal, message } from 'antd';
import AccountInformation from './component/AccountInformation/AccountInformation';
import SafetyClassify from './component/SafetyClassify/SafetyClassify';
import PhoneNmberModal from './component/PhoneNmberModal/PhoneNmberModal';
import PasswordModal from './component/PasswordModal/PasswordModal';
import PayModal from './component/PayModal/PayModal';
import BankCardModal from './component/BankCardModal/BankCardModal';
import CardMessage from './component/CardMessage/CardMessage';
import BankCardDetail from './component/BankCardDetail/BankCardDetail';
import JianzhengbaoModal from './component/JianzhengbaoModal';
import SecondAccountModal from '../common/SecondAccountModal';
import AddAuthentication from '../common/AddAuthentication';
import AttestationDetail from '../common/AttestationDetail';
import AccountState from '../common/AccountState';
import BindCardList from '../common/BindCardList';
import BindNewBankCard from '../common/BindNewBankCard';
import CommonLoading from '@/components/CommonLoading';
import { find, replace } from 'lodash';
import {
  getMessage,
  getAttestation,
  getAccountDetail,
  getBankListDetails,
  getBankBindState,
  queryPingAnAccount,
} from './service';
import { getAccountBalanceOp } from '@/services/user';
import { getApplyDetails } from '@/pages/AccountModule/applyCash/service';
import {
  getCurrentUser,
  getDifferUserDetails,
  setCurrentUserType,
} from '@/utils/authority';
import styles from './component/index.module.less';

const AccountSafety = () => {
  const location = useLocation();
	const navigate = useNavigate();
  const [personageMessage, setPersonageMessage] = useState({
    account: '',
    lastLoginTime: '',
    lastLoginIp: '',
    payPassword: '',
    authId: '',
    mobile: '',
    nickname: '',
    headImgUrl: '',
    alipayAccount: '',
    realName: '',
    type: '',
    //  accountExtend: {} //认证信息
  });
  const [accountExtend, setAccountExtend] = useState({}); //认证信息
  const [accountDetail, setAccountDetail] = useState({
    qiYe: {},
    geRen: {},
  }); //开户信息

  const [loading, setLoading] = useState(false);
  const [phoneModalSwitch, setPhoneModalSwitch] = useState(false);
  const [PasswordModalSwitch, setPasswordModalSwitch] = useState(false);
  const [PayModalSwitch, setPayModalSwitch] = useState(false);
  const [bankCardSwitch, setBankCardSwitch] = useState(false);
  const [CardSwitch, setCardSwitch] = useState(false);

  const [userAccountType, setUserType] = useState({});
  const [visible, setVisible] = useState(false); //1.见证宝补全资料 2.二类户开户绑卡一体化流程

  const [attestationVisible, setAttestationVisible] = useState(false); //实名认证类型弹窗visible
  const [detailVisible, setDetailVisible] = useState(false); //认证详情弹窗visible
  const [isOpen, setIsOpen] = useState(false); //是否是从开户流程
  const [UpgradeEnterprise, setUpgradeEnterprise] =  useState(false); //是否是升级企业账户

  const [bankListDetails, setBankListDetails] = useState([]); //绑定的银行卡列表
  const [bankBindState, setBankBindState] = useState(0); //银行卡绑定状态
  const [bankCardVisible, setBankCardVisible] = useState(false); //银行卡详情visible

  const [pingAnAccount, setPingAnAccount] = useState({}); //平安账户状态和绑卡信息
  const [detailObj, setObj] = useState({}); //提现详情

  const stageParams = useRef({});

  const { userType, bigAccount, hasOpenClassIIAccount, hasOpenAccount } =
    userAccountType;

  useEffect(() => {
    getUserType();
    pageInit();
    getAuthenticationInfo();
    queryAccountDetail();
    queryBankListDetails();
    queryBankBindState();
    getApplyDetailsFunc();
  }, []);

  // // 判断跳转l来源
  // useEffect(() => {
  //   if (location.pathname == '/account/safety') {
  //     if (location.state) {
  //       if (location.state.bindCard) {
  //         setBankCardSwitch(true);
  //       }
  //     }
  //   }
  // }, [location]);

  useEffect(() => {
    if (
      location.pathname == '/account/safety' &&
      location.state?.bindCard &&
      Object.keys(accountExtend)?.length &&
      Object.keys(userAccountType)?.length
    ) {
      navigate('/account/safety', { replace: true });
      if (userAccountType.autoState == 0 || accountExtend.accountType == 1) {
        setBankCardVisible(true);
      } else {
        setBankCardSwitch(true);
      }
    }
  }, [location, accountExtend, userAccountType]);

  //获取用户类型
  const getUserType = async () => {
    setLoading(true);
    const { data, success } = await getAccountBalanceOp({
      accountType: 1, // 1:普通账户
    });
    if (success) {
      stageParams.current = { ...stageParams.current, ...(data || {}) };
      const {
        bigAccount,
        hasOpenAccount,
        hasOpenClassIIAccount,
        enterpriseAuthModifyState,
        isSign,
      } = data;
      //hasOpenAccount(是否开通见证宝) hasOpenClassIIAccount(是否开通二类户) 1是开 0是关
      let userType;
      if (bigAccount == 1) {
        userType = 1; //大用户
      } else {
        //普通用户  （2 不处理）
        if (hasOpenAccount == 1 && enterpriseAuthModifyState == 1) {
          userType = 2; //普通老用户(需要补充资料)
        } else {
          //新用户需要开通账户
          userType = 3; //新用户
        }
      }
      //   console.log('userType=>>>', userType);
      setCurrentUserType({ ...data, userType });
      setUserType({ ...data, userType });
    }
    setLoading(false);
  };

  //获取认证信息
  const getAuthenticationInfo = async () => {
    setLoading(true);
    const { data = {}, success } = await getAttestation();
    if (success) {
      setAccountExtend(data);
    }
    setLoading(false);
  };

  //获取银行卡绑定列表
  const queryBankListDetails = async () => {
    setLoading(true);
    const { data = [] } = await getBankListDetails({
      //   accountType: 1,
    });
    setBankListDetails(data);
    setLoading(false);
  };

  //获取银行卡绑定状态
  const queryBankBindState = async () => {
    setLoading(true);
    const { data = 0 } = await getBankBindState({
      accountType: 1,
    });
    setBankBindState(data);
    setLoading(false);
  };

  //获取开户信息
  const queryAccountDetail = async () => {
    setLoading(true);
    const { success, data = {} } = await getAccountDetail();
    if (success) {
      setAccountDetail(data);
    }
    setLoading(false);
  };

  const getApplyDetailsFunc = async () => {
    const { data = {}, success } = await getApplyDetails();
    if (success) {
      setObj(data);
    }
  };

  // 获取安全信息(初始化页面)
  const pageInit = async () => {
    setLoading(true);
    const res = await getMessage({
      tenantCode: '000000',
      uuid: getCurrentUser().uuid,
    });
    if (res.code == 200) {
      setPersonageMessage({
        account: res.data.account,
        lastLoginTime: res.data.lastLoginTime,
        lastLoginIp: res.data.lastLoginIp,
        payPassword: res.data.payPassword,
        authId: res.data.authId,
        mobile: res.data.mobile,
        headImgUrl: res.data.headImgUrl,
        type: res.data.type,
        nickname: res.data.nickname,
        alipayAccount: res.data.alipayAccount,
        realName: res.data.realName,
        isBankAccount: res.data.isBankAccount,
        isBindBank: res.data.isBindBank,
        //  accountExtend: res.data.accountExtend
      });
    }
    setLoading(false);
  };

  //补充资料(认证/认证详情)
  const suppleInformation = (open) => {
    if (Object.keys(accountExtend).length > 0) {
      //已经实名认证
      if (accountExtend.accountType == 1) {
        //非企业认证
        if (userType == 1) {
          //大用户走实名认证
          setAttestationVisible(true);
        } else {
          setDetailVisible(true);
        }
      } else {
        //企业认证
        setDetailVisible(true);
      }
    } else {
      //未实名认证
      setAttestationVisible(true);
    }
    setIsOpen(open);
  };

  //升级企业账户
  const upgradeEnterpriseAccount = () => {
    // message.info('您已开通二类户，可以操作企业认证升级企业账户');
    setUpgradeEnterprise(true);
    setDetailVisible(true);
    setIsOpen(true);
  };

  //二类户未绑卡点击去绑卡(查询平安账户状态和绑卡信息)
  const handleBindCard = async () => {
    getPingAnAccount(true);
  };

  // 查询平安账户状态和绑卡信息
  const getPingAnAccount = async (isCheck) => {
    setLoading(true);
    const res = await queryPingAnAccount();
    if (res.success) {
      const { data = {} } = res;
      setPingAnAccount(data);
      if (isCheck) {
        if (data.status == 1 || data.status == 2) {
          //异常或者锁定
          setVisible('AccountState');
        } else if (data.status == 0) {
          //正常
          if (data.bindcardList && data.bindcardList.length > 0) {
            //已绑卡
            setVisible('BindCardList');
          } else {
            setVisible('new');
          }
        }
      }
    }
    setLoading(false);
  };

  const AccountInformationProps = {
    personageMessage,
    pageInit,
    //点击修密码吗事件
    passwordClick() {
      setPasswordModalSwitch(true);
    },
  };

  const SafetyClassifyProps = {
    personageMessage,
    accountExtend,
    accountDetail,
    bankBindState,
    pageInit,
    userAccountType,
    authentication(type) {
      suppleInformation(type);
    },
    //点击绑定手机号事件
    phoneNumberClick() {
      setPhoneModalSwitch(true);
    },
    //点击修密码吗事件
    passwordClick() {
      setPasswordModalSwitch(true);
    },
    //点击修改支付密码事件
    payClick() {
      if (getDifferUserDetails().parentId) {
        Modal.info({
          content: '子账号不允许设置、修改支付密码',
        });
      } else {
        setPayModalSwitch(true);
      }
    },
    //点击认证银行卡事件
    bankCardClick(bool) {
      if (bool) {
        setBankCardSwitch(true); //老绑卡流程
      } else {
        setVisible(2); //二类户开户流程
      }
    },
    //点击银行卡详情事件
    async cardMessageClick() {
      //   setCardSwitch(true);
      setBankCardVisible(true);
    },
  };

  const PhoneNmberModalProps = {
    phoneModalSwitch,
    pageInit,
    //修改绑定手机确定事件
    phoneModalOk() {
      setPhoneModalSwitch(false);
    },
    //修改绑定手机取消事件
    phoneModalNo() {
      setPhoneModalSwitch(false);
    },
  };

  const PasswordModalProps = {
    PasswordModalSwitch,
    //修改密码确定事件
    PasswordModalOk() {
      setPasswordModalSwitch(false);
    },
    //修改密码取消事件
    PasswordModalNo() {
      setPasswordModalSwitch(false);
    },
  };

  const PayModalProps = {
    PayModalSwitch,
    personageMessage,
    pageInit,
    //修改支付密码确定事件
    PayModalOk() {
      setPayModalSwitch(false);
    },
    //修改支付密码取消事件
    PayModalNo() {
      setPayModalSwitch(false);
    },
  };

  const BankCardModalProps = {
    bankCardSwitch,
    accountExtend,
    userAccountType,
    pageInit,
    //绑定银行卡弹窗关闭事件
    bankCardClose() {
      setBankCardSwitch(false);
    },
  };

  const CardMessageProps = {
    bigAccount,
    CardSwitch,
    pageInit,
    personageMessage,
    // 银行卡信息关闭事件
    CardClose() {
      setCardSwitch(false);
    },
  };

  const openAccountModalProps = {
    title: userType == 2 ? '补充资料' : '开通账户',
    handleOk() {
      getUserType();
      pageInit();
      setVisible(false);
    },
    handleCancel() {
      setVisible(false);
    },
  };

  //实名认证
  const AddAuthenticationProps = {
    visible: attestationVisible,
    accountExtend,
    userAccountType,
    handleCancel() {
      setAttestationVisible(false);
      setIsOpen(false);
    },
    handleOk() {
      setAttestationVisible(false);
      getAuthenticationInfo();
      if (isOpen) {
        //走开通账户流程
        setDetailVisible(true);
      }
    },
  };

  //认证详情
  const AttestationDetailProps = {
    visible: detailVisible,
    isOpen: isOpen, //是否是开户
    UpgradeEnterprise, //是否是升级企业账户
    accountExtend,
    userAccountType,
    handleCancel() {
      setDetailVisible(false);
      setIsOpen(false);
      setUpgradeEnterprise(false);
    },
    handUpdateAccountDetail() {
      //修改认证信息之后更新账户信息
      queryAccountDetail();
      getAuthenticationInfo();
    },
    handUpdataData() {
      //更新所有的数据
      getUserType();
      pageInit();
      getAuthenticationInfo();
      queryAccountDetail();
      queryBankListDetails();
      queryBankBindState();
    },
    handleOk() {
      getUserType();
      pageInit();
      getAuthenticationInfo();
      queryAccountDetail();
      queryBankListDetails();
      queryBankBindState();
      setDetailVisible(false);
      setIsOpen(false);
      setUpgradeEnterprise(false);
    },
  };

  //银行卡详情
  const BankCardDetailProps = {
    visible: bankCardVisible,
    accountExtend,
    bankListDetails,
    userAccountType,
    detailObj,
    pageInit,
    current: stageParams.current,
    //见证宝去绑卡
    bankCardClick() {
      setBankCardSwitch(true); //老绑卡流程
    },
    handleCancel() {
      setBankCardVisible(false);
    },
    updateBankState() {
      //更新银行卡状态
      pageInit();
      queryBankListDetails();
      queryBankBindState();
      queryAccountDetail();
      getApplyDetailsFunc();
    },
  };

  //账号状态
  const AccountStateProps = {
    visible: visible == 'AccountState',
    pingAnAccount,
    handleCancel() {
      setVisible(false);
    },
    handleOk() {
      setVisible(false);
    },
  };

  //绑定银行卡列表
  const BindCardListProps = {
    noMesRequire: false, //需验证码验证
    visible: visible == 'BindCardList',
    accountExtend,
    pingAnAccount,
    handleCancel() {
      setVisible(false);
    },
    handleOk() {
      getPingAnAccount(false);
      setVisible(false);
      queryBankListDetails();
      queryBankBindState();
      queryAccountDetail();
    },
    handleUnBindOk() {
      //解绑卡
      getPingAnAccount(false);
    },
  };

  //绑定新银行卡
  const BindNewBankCardProps = {
    accountExtend,
    handleOk() {
      setVisible(false);
      queryBankListDetails();
      queryBankBindState();
      queryAccountDetail();
    },
    handleCancel() {
      setVisible(false);
    },
  };

  const renderBtn = useMemo(() => {
    if ((userType == 2 || userType == 3) && !hasOpenClassIIAccount) {
      //未开户
      return (
        <span
          onClick={() => suppleInformation(true)}
          className={styles.noticeBtn}
        >
          {userType == 2 ? '补充资料' : '开通账户'}
        </span>
      );
    } else if ((userType == 2 || userType == 3) && hasOpenClassIIAccount) {
      //已开户
      if (bankListDetails && bankListDetails.length > 0) {
        const ccassIIAccount = find(bankListDetails, ['channelType', 1]); //二类户
        if (ccassIIAccount && !ccassIIAccount.bankNo) {
          //已户未绑卡
          return (
            <span onClick={() => handleBindCard()} className={styles.noticeBtn}>
              {userType == 2 ? '补充资料' : '开通账户'}
            </span>
          );
        }
      }
    }
  }, [userAccountType, accountExtend, bankListDetails]);



  return (
    <>
      <div className="zjf-container-nof">
        <h1
          className="page-title common-color3"
          style={{ marginBottom: 15, fontSize: 18 }}
        >
          账号安全&nbsp;&nbsp;
          {renderBtn}
          {hasOpenClassIIAccount == 1 && hasOpenAccount == 0 ? (
            <span
              onClick={() => {
                upgradeEnterpriseAccount();
              }}
              style={{ marginLeft: '10px' }}
              className={styles.noticeBtn}
            >
              升级企业账户
            </span>
          ) : (
            ''
          )}
        </h1>
        <AccountInformation {...AccountInformationProps}></AccountInformation>
        <SafetyClassify {...SafetyClassifyProps}></SafetyClassify>
        <PhoneNmberModal {...PhoneNmberModalProps}></PhoneNmberModal>
        <PasswordModal {...PasswordModalProps}></PasswordModal>
        <PayModal {...PayModalProps}></PayModal>
        <BankCardModal {...BankCardModalProps}></BankCardModal>
        <CardMessage {...CardMessageProps}></CardMessage>
        {visible == 1 && <JianzhengbaoModal {...openAccountModalProps} />}
        {visible == 2 && <SecondAccountModal {...openAccountModalProps} />}

        {/* 实名认证} */}
        {attestationVisible && (
          <AddAuthentication {...AddAuthenticationProps} />
        )}
        {/* 认证详情} */}
        {detailVisible && <AttestationDetail {...AttestationDetailProps} />}

        {/* 银行卡详情} */}
        {bankCardVisible && <BankCardDetail {...BankCardDetailProps} />}

        {/* 账户状态 */}
        {visible == 'AccountState' && <AccountState {...AccountStateProps} />}

        {/* 绑定银行卡列表 */}
        {visible == 'BindCardList' && <BindCardList {...BindCardListProps} />}

        {/* 新绑定银行卡 */}
        {visible == 'new' && <BindNewBankCard {...BindNewBankCardProps} />}

      </div>
      <CommonLoading loading={loading} />
    </>
  );
};

export default React.memo(AccountSafety, (pre, nextProps) => {
  if (nextProps.location.state) {
    return false;
  } else {
    return true;
  }
});
